import React, { useState, useEffect } from 'react';
import './Address.css';
import { useNavigate } from 'react-router-dom';
import { NavBar } from 'antd-mobile'
// 从localStorage加载地址数据
const loadAddressesFromStorage = () => {
  const savedAddresses = localStorage.getItem('addresses');
  return savedAddresses ? JSON.parse(savedAddresses) : [
    {
      id: 1,
      name: '张三',
      phone: '13800138000',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',
      detail: '建国路88号现代城A座2001室',
      isDefault: true
    },
    {
      id: 2,
      name: '李四',
      phone: '13900139000',
      province: '上海市',
      city: '上海市',
      district: '浦东新区',
      detail: '张江高科技园区科苑路88号',
      isDefault: false
    }
  ];
};

const Address = () => {
  const navigate = useNavigate();
  const [addresses, setAddresses] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [currentAddress, setCurrentAddress] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  });

  const back = () => {
    navigate(-1)
}

  // 初始化时从localStorage加载数据
  useEffect(() => {
    const loadedAddresses = loadAddressesFromStorage();
    setAddresses(loadedAddresses);
  }, []);

  // 保存地址数据到localStorage
  const saveAddressesToStorage = (addressesToSave) => {
    localStorage.setItem('addresses', JSON.stringify(addressesToSave));
  };

  // 打开添加地址模态框
  const openAddModal = () => {
    setCurrentAddress(null);
    setFormData({
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: '',
      isDefault: false
    });
    setShowModal(true);
  };

  // 打开编辑地址模态框
  const openEditModal = (address) => {
    setCurrentAddress(address);
    setFormData({ ...address });
    setShowModal(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setShowModal(false);
  };

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData({
      ...formData,
      [name]: type === 'checkbox' ? checked : value
    });
  };

  // 提交表单
  const handleSubmit = (e) => {
    e.preventDefault();
    
    let updatedAddresses;
    
    if (currentAddress) {
      // 编辑现有地址
      updatedAddresses = addresses.map(addr => 
        addr.id === currentAddress.id ? { ...formData, id: currentAddress.id } : addr
      );
    } else {
      // 添加新地址
      const newAddress = {
        ...formData,
        id: addresses.length > 0 ? Math.max(...addresses.map(a => a.id)) + 1 : 1
      };
      
      // 如果设置为默认地址，则取消其他地址的默认状态
      if (formData.isDefault) {
        updatedAddresses = addresses.map(addr => ({
          ...addr,
          isDefault: false
        }));
        updatedAddresses.push(newAddress);
      } else {
        updatedAddresses = [...addresses, newAddress];
      }
    }
    
    setAddresses(updatedAddresses);
    saveAddressesToStorage(updatedAddresses);
    closeModal();
  };

  // 删除地址
  const deleteAddress = (id) => {
    if (window.confirm('确定要删除该地址吗？')) {
      const updatedAddresses = addresses.filter(addr => addr.id !== id);
      setAddresses(updatedAddresses);
      saveAddressesToStorage(updatedAddresses);
    }
  };

  // 设置默认地址
  const setDefaultAddress = (id) => {
    const updatedAddresses = addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === id
    }));
    setAddresses(updatedAddresses);
    saveAddressesToStorage(updatedAddresses);
  };

  return (
    <div className="address-management">
      <NavBar onBack={back}>地址管理</NavBar>
      <div className="address-header">
        <h2>收货地址</h2>
        <button className="add-btn" onClick={openAddModal}>
          <span>+</span> 新增地址
        </button>
      </div>

      <div className="address-list">
        {addresses.length === 0 ? (
          <div className="empty-address">
            <div className="empty-icon">📭</div>
            <p>您还没有添加收货地址</p>
            <button className="add-btn" onClick={openAddModal}>
              <span>+</span> 新增地址
            </button>
          </div>
        ) : (
          addresses.map(address => (
            <div 
              key={address.id} 
              className={`address-item ${address.isDefault ? 'default' : ''}`}
            >
              <div className="address-info">
                <div className="address-header">
                  <span className="name">{address.name}</span>
                  <span className="phone">{address.phone}</span>
                  {address.isDefault && <span className="default-tag">默认</span>}
                </div>
                <div className="address-detail">
                  {address.province}{address.city}{address.district}{address.detail}
                </div>
              </div>
              <div className="address-actions">
                <button onClick={() => openEditModal(address)}>编辑</button>
                <button onClick={() => deleteAddress(address.id)}>删除</button>
                {!address.isDefault && (
                  <button onClick={() => setDefaultAddress(address.id)}>设为默认</button>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* 添加/编辑地址模态框 */}
      {showModal && (
        <div className="modal-overlay">
          <div className="modal">
            <div className="modal-header">
              <h3>{currentAddress ? '编辑收货地址' : '新增收货地址'}</h3>
              <span className="close-btn" onClick={closeModal}>×</span>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>收货人：</label>
                <input
                  type="text"
                  name="name"
                  value={formData.name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="form-group">
                <label>手机号码：</label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  required
                  pattern="[0-9]{11}"
                />
              </div>
              <div className="form-group">
                <label>所在地区：</label>
                <div className="region-inputs">
                  <input
                    type="text"
                    name="province"
                    placeholder="省/直辖市"
                    value={formData.province}
                    onChange={handleInputChange}
                    required
                  />
                  <input
                    type="text"
                    name="city"
                    placeholder="市"
                    value={formData.city}
                    onChange={handleInputChange}
                    required
                  />
                  <input
                    type="text"
                    name="district"
                    placeholder="区/县"
                    value={formData.district}
                    onChange={handleInputChange}
                    required
                  />
                </div>
              </div>
              <div className="form-group">
                <label>详细地址：</label>
                <input
                  type="text"
                  name="detail"
                  value={formData.detail}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div className="form-group checkbox-group">
                <label>
                  <input
                    type="checkbox"
                    name="isDefault"
                    checked={formData.isDefault}
                    onChange={handleInputChange}
                  />
                  设为默认地址
                </label>
              </div>
              <div className="form-actions">
                <button type="button" className="cancel-btn" onClick={closeModal}>
                  取消
                </button>
                <button type="submit" className="save-btn">
                  保存
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Address;